package com.hfzy.ihk.web.linkcall.utils;

import com.alibaba.fastjson.JSON;
import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.common.util.http.HttpClientUtils;
import com.hfzy.ihk.facade.userCenter.entity.Priv;
import com.hfzy.ihk.facade.userCenter.entity.UserInfo;
import com.hfzy.ihk.web.linkcall.context.Context;
import com.hfzy.ihk.web.oauth.client.utils.UserUtil;
import org.apache.tomcat.util.buf.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class UserUtils {
    private static Logger logger = LoggerFactory.getLogger(UserUtils.class);

    public static String crmHttpUrl;
    public static String userServerUrl;

    @Value("${crm.http.url}")
    public void setCrmHttpUrl(String crmHttpUrl) {
        this.crmHttpUrl = crmHttpUrl;
    }


    @Value("${user-server.url}")
    public  void setUserServerUrl(String userServerUrl) {
        this.userServerUrl = userServerUrl;
    }

    public static OAuth2RestOperations restOperations;
    public static RestTemplate restTemplate;

    @Autowired(required = false)
    public void setRestOperations(OAuth2RestOperations restOperations){
        this.restOperations = restOperations;
    }

    @Autowired(required = false)
    public void setRestTemplate(RestTemplate restTemplate){
        this.restTemplate = restTemplate;
    }

    //获取当前的userId
    public static Long getCurrentUserId() {
        //如果当前请求方式为 ihkapp(小程序) 情况下，没有当前的登录用户，取当前请求的createUserId
        try{
            if("ihkapp".equals(UserUtil.getClickId())){
                if(Context.contextIntf.getRequest()!=null){
                    String createUserId = Context.contextIntf.getRequest().getParameter("createUserId");
                    if(!Utils.isNullString(createUserId) && Utils.isNumber(createUserId)){
                        return Long.parseLong(createUserId);
                    }
                }
            }else {
                if(UserUtil.getLoginUser()!=null){
                    return Long.parseLong(UserUtil.getLoginUser().getId().toString());
                }
            }
        }catch (Exception e){
        }
        return null;
    }

    // 此方法仅返回用户信息
    public static List<UserInfo> getUserByIds(List<String> uIds) {
        List<UserInfo> userInfos = null;
        try {
            long timeStamp = System.currentTimeMillis();
            uIds = uIds.stream().filter(it -> it != null && Utils.isNumber(it)).distinct().collect(Collectors.toList());//去重复的uid
            String requestUrl = userServerUrl+"/users/queryUserListByIds/"+StringUtils.join(uIds, ',');
            String result = HttpClientUtils.getMethod(requestUrl);
            long endTimeStamp = System.currentTimeMillis();
            logger.info("getUserByIds 耗时：" + (endTimeStamp - timeStamp) + "ms");
            if (!Utils.isNullString(result) && !"[null]".equals(result))
                userInfos = JSON.parseArray(result, UserInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("根据id获取用户信息异常" + e.getMessage());
            userInfos = null;
        }
        return userInfos;
    }

    public static UserInfo getUserById(String uId) {
        List<String> uIds = new ArrayList<>();
        uIds.add(uId);
        List<UserInfo> userInfos = getUserByIds(uIds);
        return userInfos!=null?userInfos.get(0):null;
    }


    //此方法返回用户信息 --》含权限、角色信息
    public static List<UserInfo> getSimpleUserByIds(List<String> uIds) {
        List<UserInfo> userInfos = null;
        try {
            long timeStamp = System.currentTimeMillis();
            uIds = uIds.stream().filter(it -> it != null && Utils.isNumber(it)).distinct().collect(Collectors.toList());//去重复的uid
            String requestUrl = userServerUrl+"/users/querySimpleUserInfo/"+StringUtils.join(uIds, ',');
            String result = HttpClientUtils.getMethod(requestUrl);
            long endTimeStamp = System.currentTimeMillis();
            logger.info("getUserByIds 耗时：" + (endTimeStamp - timeStamp) + "ms");
            if (!Utils.isNullString(result) && !"[null]".equals(result))
                userInfos = JSON.parseArray(result, UserInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("根据id获取用户信息异常" + e.getMessage());
            userInfos = null;
        }
        return userInfos;
    }

    public static UserInfo getSimpleUserById(String uId) {
        List<String> uIds = new ArrayList<>();
        uIds.add(uId);
        List<UserInfo> userInfos = getSimpleUserByIds(uIds);
        return userInfos!=null?userInfos.get(0):null;
    }

    public static Map<Integer, String> getUserNameMap(List<String> uIds) {
        Map<Integer, String> userMap = new HashMap<>();
        List<UserInfo> userInfos = getUserByIds(uIds);
        if (userInfos != null && !userInfos.isEmpty()) {
            userMap = userInfos.stream().collect(Collectors.toMap(UserInfo::getId, UserInfo::getUsername));
        }
        return userMap;
    }

    public static Map<Integer, String> getUserNameMap(Long... uIds) {
        Map<Integer, String> userMap = new HashMap<>();
        List<String> nUIds = new ArrayList<>();
        for (Long uId : uIds) {
            nUIds.add(uId.toString());
        }
        List<UserInfo> userInfos = getUserByIds(nUIds);
        if (userInfos != null && !userInfos.isEmpty()) {
            userMap = userInfos.stream().collect(Collectors.toMap(UserInfo::getId, UserInfo::getUsername));
        }
        return userMap;
    }


    /**
     * 是否可以查所有的数据
     */
    public static boolean canSearchAll(Long userId) {
        List<String> nUIds = new ArrayList<>();
        nUIds.add(userId.toString());
        List<UserInfo> userInfos = getUserByIds(nUIds);
        if (userInfos != null && !userInfos.isEmpty()) {
            return hasSearchAllPriv(Utils.getFirst(userInfos));
        }
        return false;
    }


    /**
     * 获取客查询的用户ids
     * */
    public static boolean hasSearchAllPriv(UserInfo userInfo){
        boolean flag = false;
        if (userInfo.getPrivs()!= null && !userInfo.getPrivs().isEmpty()) {
            for (Priv priv:userInfo.getPrivs()){
                if("linkcall-es-manage".equals(priv.getPrivName())){
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }



}
